const crypto = require('crypto');
const fs = require('fs');
const NodeRSA = require('node-rsa');
// 生成 RSA 密钥对
function generateKeyPair() {
    const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
        modulusLength: 2048,
        publicKeyEncoding: {
            type: 'spki',
            format: 'pem'
        },
        privateKeyEncoding: {
            type: 'pkcs8',
            format: 'pem'
        }
    });

    return {
        publicKey,
        privateKey
    };
}

// 保存密钥对到文件
const saveKeyPairToFile = (publicKey, privateKey) => {
    fs.writeFileSync('public_key.pem', publicKey);
    fs.writeFileSync('private_key.pem', privateKey);
    console.log('Public key saved to public_key.pem');
    console.log('Private key saved to private_key.pem');
};

// 从文件中读取密钥对
const readKeyPairFromFile = () => {
    let publicKey = '';
    let privateKey = '';

    try {
        publicKey = fs.readFileSync('public_key.pem', 'utf8');
        privateKey = fs.readFileSync('private_key.pem', 'utf8');
    } catch (error) {
        // 文件不存在，生成新的密钥对
        const keyPair = generateKeyPair();
        saveKeyPairToFile(keyPair.publicKey, keyPair.privateKey);
        publicKey = keyPair.publicKey;
        privateKey = keyPair.privateKey;
    }

    return {
        publicKey,
        privateKey
    };
};

// 使用公钥加密数据
const encryptWithPublicKey = (data) => {
    const { publicKey } = readKeyPairFromFile();
    const encrypt = new NodeRSA(publicKey);
    encrypt.setOptions({encryptionScheme: 'pkcs1'})
    const encryptedData = encrypt.encrypt(data, 'base64');
    return encryptedData
};

// 使用私钥解密数据
const decryptWithPrivateKey = (encryptedData) => {
    const { privateKey } = readKeyPairFromFile();
    const decrypt = new NodeRSA(privateKey);
    decrypt.setOptions({encryptionScheme: 'pkcs1'})
    const decryptedData = decrypt.decrypt(encryptedData, 'utf8');
    return decryptedData
};

module.exports = {
    encryptWithPublicKey,
    decryptWithPrivateKey
};

// 自动创建密钥对并保存到文件
try {
    readKeyPairFromFile();
} catch (error) {
    console.error('Error:', error);
}
// const ds = decodeURIComponent('aFiANl6YIn56B%2FpGlP0EhCc%2B9kKLb5IH61At%2B7COVeqdG79CYbjLRom%2Fu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2FtJkWwVHHRyJUj4mByH39232wVbZebOX66cNevv26xpnHCLX4OCeJMnuCJM%2FzXyZKqQhAH1QCRAtQMw1ufwR8WCm5gVmoey1UGsqO2niqHmpcLlUXvzmtRecciep%2F1gWIt513Kj%2FZFRvAEgW2KIFJlmcNQ4nFi8O7SBNoK9KPL3NAvhC%2BNP3tMUDgoJHg9j42MOImPN48DkW3KCCLycWw0sNQJWBSBpCQbL76hH4HOkvEVBT52D%2FUe%2BOB2Leal9u6xjoeVty0%2BvnuuJLKrKQHIMP%2FYTr%2BCSPfKGWWgI8AExKbxC%2BlMby%2BUmeZENVfpU3lp172dCVHq0GksRZyx6MhdLguJbT%2BhLedoeUYcDdZuOpEQqcKrpiOeb3d2%2BzP22pyQ7pjfLcCSjsw%2BSavo2kRWr6H0BZpkTIjYUuHpZ8O4nQ2lGLiEWMmTn4JGcQ8ctdflxpijI5eNNzpIzPBqiVc1ujGFrcfn%2BM207kZ8FydXooQHpfX9kKUxTXMDBEx7X%2BjmyjxqvvFywqFtkp6eCU8220eCuN9CmpBI2lqBSjcHhFhc0iMiZI68%2F0o4bXKbIMcbwxfovRa0RDg7WHmc2dlzWdRbPVapqzwWNDkxVvWSbXpK8ytVq%2BQaePAEyRQYKg%3D')
// console.log(decryptWithPrivateKey(ds),'fff')
// 重新生产密钥
// const keyPair = generateKeyPair();
// saveKeyPairToFile(keyPair.publicKey, keyPair.privateKey);